package com.unohacha.qqj.fzdr.personal.view.activity;

import android.content.res.Resources;
import android.support.design.widget.TabLayout;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.unohacha.qqj.fzdr.R;
import com.unohacha.qqj.fzdr.common.bean.HttpResult;
import com.unohacha.qqj.fzdr.common.bean.ReleaseBean;
import com.unohacha.qqj.fzdr.common.bean.ReleaseManagementBean;
import com.unohacha.qqj.fzdr.common.bean.ThreeLevelBean;
import com.unohacha.qqj.fzdr.common.bean.TwoLevelBean;
import com.unohacha.qqj.fzdr.common.http.RetrofitManager;
import com.unohacha.qqj.fzdr.personal.adapter.ReleaseAdapter;
import com.unohacha.qqj.fzdr.util.Prefer;
import com.unohacha.qqj.fzdr.util.ToastUtils;
import com.unohacha.qqj.fzdr.view.FlowLayout;
import com.unohacha.qqj.mylibrary.base.BaseActivity;
import com.zyyoona7.popup.EasyPopup;

import java.lang.reflect.Field;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 收藏管理
 */
public class CollectionActivity extends BaseActivity {

    private static final String TAG = "Collection";

    @BindView(R.id.common_back)
    ImageView commonBack;
    @BindView(R.id.common_title)
    RadioButton commonTitle;
    @BindView(R.id.common_title2)
    RadioButton commonTitle2;
    @BindView(R.id.common_right_image)
    ImageView rightImage;

    @BindView(R.id.mRefreshLayout)
    SmartRefreshLayout mRefreshLayout;

    private List<ReleaseManagementBean> list;
    private ReleaseAdapter adapter;

    private int page = 1;

    private LayoutInflater mInflater;
    private List<TwoLevelBean> levelBeans;

    // 保存供应/需求状态 1：供应 2：需求
    private String firstLevel = "1";

    // 二级标题
    @BindView(R.id.tb_two_level)
    TabLayout tbTwoLevel;

    @OnClick(R.id.iv_level_more)
    void onLevelMoreClick() {
        int selected = tbTwoLevel.getSelectedTabPosition();
        List<ThreeLevelBean> threeLevelBeans = levelBeans.get(selected).getTwo();
        if (threeLevelBeans.size() > 0) {
            FlowLayout contentView = (FlowLayout) LayoutInflater.from(this).inflate(R.layout.flowlayout, null);

            for (ThreeLevelBean threeLevelBean : threeLevelBeans) {
                TextView tv = (TextView) mInflater.inflate(R.layout.item_textview, contentView, false);
                tv.setText(threeLevelBean.getName());
                final String txt = threeLevelBean.getId();
                tv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ToastUtils.showT(txt);
                        initDataRelease(txt);
                    }
                });
                contentView.addView(tv);
            }

            EasyPopup popWindow = EasyPopup.create()
                    .setContentView(contentView)
                    .setWidth(ViewGroup.LayoutParams.MATCH_PARENT)
                    //是否允许点击PopupWindow之外的地方消失
                    .setFocusAndOutsideEnable(true)
                    .apply();

            popWindow.showAsDropDown(tbTwoLevel);
        } else {
            ToastUtils.showT("没有数据");
        }
    }


    @Override
    protected int getLayoutId() {
        return R.layout.activity_collection;
    }

    @OnClick(R.id.common_back)
    void onBackClick() {
        finish();
    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    @Override
    protected void initView() {
//        super.initView();
        commonTitle.setText("供应收藏");
        commonTitle2.setText("需求收藏");
        rightImage.setVisibility(View.INVISIBLE);
    }

    // 加载发布数据
    private void initDataRelease(final String supply_cate_two) {
        // 测试数据
        showLoading();
        Log.d(TAG, "onLevelMoreClick: " + Prefer.getInstance().getToken() + "/" + firstLevel + "/" + levelBeans.get(0).getId() + "/" + page);
        Call<HttpResult<ReleaseBean>> call1 = RetrofitManager.getInstance()
                .supplyReleaseManagement(Prefer.getInstance().getToken(), firstLevel, levelBeans.get(tbTwoLevel.getSelectedTabPosition()).getId(), supply_cate_two, page);
        call1.enqueue(new Callback<HttpResult<ReleaseBean>>() {
            @Override
            public void onResponse(Call<HttpResult<ReleaseBean>> call, Response<HttpResult<ReleaseBean>> response) {
                ReleaseBean data = response.body().getData();
                if (data != null) {
                    upDataRelease(data);
                } else {
                    Log.d(TAG, "onResponse: " + "加载失败！");
                    upDataRelease(new ReleaseBean());
                }
            }

            @Override
            public void onFailure(Call<HttpResult<ReleaseBean>> call, Throwable t) {
                closeRefresh();
            }
        });
    }

    // 更新数据
    public void upDataRelease(ReleaseBean data) {
        Log.d(TAG, "upDataRelease: " + data);
//        Toast.makeText(getApplicationContext(), data.getTotal(), Toast.LENGTH_SHORT).show();
//        rcReleaseManagement.setAdapter(new ReleaseAdapter(R.layout.item_release, data.getData()));

        if (data.getData() == null) {
            Toast.makeText(getApplicationContext(), "当前分类无数据", Toast.LENGTH_SHORT).show();
            list.clear();
            adapter.notifyDataSetChanged();
        } else if (page == 1) {
            list.clear();
            list.addAll(data.getData());
            adapter.notifyDataSetChanged();
        } else {
            list.addAll(data.getData());
            adapter.notifyDataSetChanged();
        }
        tbTwoLevel.post(new Runnable() {
            @Override
            public void run() {
                setIndicator(tbTwoLevel, 50, 50);
            }
        });
        closeRefresh();
        hideLoading();
    }

    private void closeRefresh() {
        if (mRefreshLayout.isRefreshing()) {
            mRefreshLayout.finishRefresh();
        }
        if (mRefreshLayout.isLoading()) {
            mRefreshLayout.finishLoadmore();
        }
    }

    public void setIndicator(TabLayout tabs, int leftDip, int rightDip) {
        Class<?> tabLayout = tabs.getClass();
        Field tabStrip = null;
        try {
            tabStrip = tabLayout.getDeclaredField("mTabStrip");
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        tabStrip.setAccessible(true);
        LinearLayout llTab = null;
        try {
            llTab = (LinearLayout) tabStrip.get(tabs);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        int left = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, leftDip, Resources.getSystem().getDisplayMetrics());
        int right = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, rightDip, Resources.getSystem().getDisplayMetrics());

        for (int i = 0; i < llTab.getChildCount(); i++) {
            View child = llTab.getChildAt(i);
            child.setPadding(0, 0, 0, 0);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
            params.leftMargin = left;
            params.rightMargin = right;
            child.setLayoutParams(params);
            child.invalidate();
        }
    }
}
